package com.acme.bankapp.service.bank;

import com.acme.bankapp.domain.bank.Bank;
import com.acme.bankapp.domain.bank.Client;
import com.acme.bankapp.domain.bank.account.CheckingAccount;
import com.acme.bankapp.domain.bank.exception.BadStringToParseClient;
import com.acme.bankapp.domain.bank.exception.ClientExistsException;
import com.acme.bankapp.domain.bank.exception.NotEnoughFundsException;
import com.acme.bankapp.domain.bank.exception.TooManyClients;

import java.io.*;

public class BankService {

    private static final String fileBackupName = "backup.txt";

    public static void addClient(Bank bank, Client client) throws ClientExistsException, TooManyClients {
        bank.addClient(client);
    }

    public static void printMaximumAmountToWithdraw(Bank bank) {
        for (Client client : bank.getClients()) {
            if (client != null) {
                System.out.println(client);
            }
        }
    }

    public static void modifyBank(Bank bank) {
        for (Client client : bank.getClients())
            try {
                client.getAccount().depositMoney(10);
                client.getAccount().withdrawMoney(50);
                if (client.getAccount() instanceof CheckingAccount) {
                    client.getAccount().withdrawMoney(((CheckingAccount) client.getAccount()).getOverdraft());
                    client.getAccount().depositMoney(70);
                }
            } catch (NotEnoughFundsException e) {
                System.out.println(e);
            }

        try {
            saveBank(bank, fileBackupName);
        } catch (IOException e) {
            System.out.println("Writing file error");
            e.printStackTrace();
        }

    }

    public static void saveBank(Bank bank, String fileName) throws IOException {
        try (BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(fileName))))) {
            for (Client client : bank.getClients()) {
                bw.write(BankDataLoaderService.clientToString(client));
            }
        }
    }

    public static Bank readBank(String fileName) throws IOException {
        Bank bank = new Bank();
        try (BufferedReader bis = new BufferedReader(new InputStreamReader(new FileInputStream(fileName)))) {
            String s;
            while ((s = bis.readLine()) != null) {
                try {
                    bank.addClient(BankDataLoaderService.parseString(s));
                } catch (ClientExistsException | TooManyClients | BadStringToParseClient e) {
                    System.out.println(e);
                }
            }
        }
        return bank;
    }


}
